<?php
declare (strict_types = 1);

namespace app\common\command\pachong\book;

use app\common\model\pachong\book\PachongBook;
use app\common\model\pachong\PachongProxyIp;
use app\common\model\Tool;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use function think\p;

class CommandBook extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('hello')
            ->setDescription('the hello command');
    }

    protected function execute(Input $input, Output $output)
    {
        $this->shuluxiaoshuo();

    }

    // 书路小说网
    public function shuluxiaoshuo()
    {
        // 首先录入书名
        for ($i =6;$i<=1593;$i++){
            echo "当前开始查第{$i}页数据".PHP_EOL;
            $url = "https://www.shulu.la/top/allvisit/".$i.".html";
            $result = $this->getContent($url);

            foreach ($result as $val){
                // 循环查询这本书是否存在,存在就不插入了
                $hasBook = PachongBook::instance()->where(['name'=>$val['name']])->count();
                if($hasBook > 0){
                    echo "重复书名：《{$val['name']}》".PHP_EOL;
                    continue;
                }
                $postData = array(
                    'name' => $val['name'],
                    'web_url' =>  $val['web_url'],
                );
                PachongBook::instance()->insert($postData);
                echo "插入书名：《{$val['name']}》".PHP_EOL;
            }
            sleep(10);
        }
    }

    public function getContent($url)
    {
        $ProxyIp = PachongProxyIp::instance()->getProxyIp();
        $zxurl = "127.0.0.1:8000/getBookSlxs?proxy_ip=".$ProxyIp."&url=" . $url;
        $time = date("Y-m-d H:i:s", time());
        echo "【{$time}】执行python请求地址:".$zxurl.PHP_EOL;
        $result = Tool::getCurl($zxurl);
        $time = date("Y-m-d H:i:s", time());
        echo "【{$time}】执行python返回值:".json_encode($result,JSON_UNESCAPED_UNICODE).PHP_EOL;
        if($result == null){
            sleep(10);
            return $this->getContent($url);
        }
        if($result['code'] == 200){
            return $result['data'];
        }elseif ($result['code'] == 500){
            sleep(10);
            return $this->getContent($url);
        }else{
            return array();
        }
    }
}
